import zipfile
import os
from datetime import datetime
#zip文件解压缩,zip_path: str, extract_to: str
def unzip_file(zip_path, extract_to):
    try:
        with zipfile.ZipFile(zip_path, 'r') as zip_ref:
            zip_ref.extractall(extract_to)
        return True
    except zipfile.BadZipFile:
        print(f"错误: {zip_path} 不是有效的ZIP文件")
        return False
    except Exception as e:
        print(f"解压失败: {zip_path}, 错误: {str(e)}")
        return False


# 确认zip文件夹是否有压缩文件
def has_zip_files(directory):
    # 定义空数组来存储zip文件名 
    zip = []
    for filename in os.listdir(directory):
        # 过滤掉以._开头的系统文件和隐藏文件
        if filename.endswith('.zip') and not filename.startswith('._') and not filename.startswith('.'):
            zip.append(filename)

    if zip:
        return zip
    return False
# 读取当前目录下的md文件
def read_md_files(directory):
    md_files = []
    for filename in os.listdir(directory):
        if filename.endswith('.md'):
            md_files.append(filename)
    if md_files:
        return md_files
    return False
# 读取md文件的内容
def read_md_file_content(file_path):
    """读取Markdown文件内容，支持多种编码"""
    try:
        # 首先尝试UTF-8编码
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.read()
        return content
    except UnicodeDecodeError:
        # 如果UTF-8失败，尝试GBK编码
        try:
            with open(file_path, 'r', encoding='gbk') as file:
                content = file.read()
            return content
        except UnicodeDecodeError:
            # 如果GBK也失败，尝试latin-1编码
            try:
                with open(file_path, 'r', encoding='latin-1') as file:
                    content = file.read()
                return content
            except Exception as e:
                raise Exception(f"无法读取文件 {file_path}，尝试了多种编码都失败: {str(e)}")
    except FileNotFoundError:
        raise Exception(f"文件不存在: {file_path}")
    except PermissionError:
        raise Exception(f"没有权限读取文件: {file_path}")
    except Exception as e:
        raise Exception(f"读取文件时发生错误: {str(e)}")

# 获取所有ZIP文件信息
def get_zip_objects():
    """获取所有ZIP文件的处理结果"""
    if not has_zip_files('zip'):
        return []
    
    zip_objects = []
    for zip_file in has_zip_files('zip'):
        object = {}
        # 拼接zip文件的完整路径
        zip_path = os.path.join('zip', zip_file)
        # 使用zip文件名创建一个文件夹
        extract_folder = os.path.splitext(zip_file)[0]
        extract_path = 'unzip/' + extract_folder
        
        # 获取ZIP文件的时间信息
        try:
            stat = os.stat(zip_path)
            # 在macOS上，st_birthtime更准确表示创建时间
            if hasattr(stat, 'st_birthtime'):
                created_time = datetime.fromtimestamp(stat.st_birthtime).strftime('%Y-%m-%d %H:%M:%S')
                created_timestamp = stat.st_birthtime
            else:
                # 回退到ctime（在某些系统上可能是inode修改时间）
                created_time = datetime.fromtimestamp(stat.st_ctime).strftime('%Y-%m-%d %H:%M:%S')
                created_timestamp = stat.st_ctime
            
            modified_time = datetime.fromtimestamp(stat.st_mtime).strftime('%Y-%m-%d %H:%M:%S')
            file_size = stat.st_size
        except Exception as e:
            created_time = '未知'
            modified_time = '未知'
            created_timestamp = 0
            file_size = 0
        
        # 解压到当前目录下的unzip文件夹
        success = unzip_file(zip_path, extract_path)
        
        if success:
            md_files = read_md_files(extract_path)
            object['id'] = len(zip_objects) + 1
            object['zip_name'] = zip_file
            object['zip_file'] = zip_path
            object['extract_path'] = extract_path
            object['md_files'] = md_files if md_files else []
            object['file_count'] = len(md_files) if md_files else 0
            object['status'] = 'success'
            object['created_time'] = created_time
            object['modified_time'] = modified_time
            object['created_timestamp'] = created_timestamp
            object['file_size'] = file_size
        else:
            object['id'] = len(zip_objects) + 1
            object['zip_name'] = zip_file
            object['zip_file'] = zip_path
            object['extract_path'] = extract_path
            object['md_files'] = []
            object['file_count'] = 0
            object['status'] = 'failed'
            object['created_time'] = created_time
            object['modified_time'] = modified_time
            object['created_timestamp'] = created_timestamp
            object['file_size'] = file_size
        
        zip_objects.append(object)
    
    # 按创建时间倒序排列（最新的在前面）
    zip_objects.sort(key=lambda x: x.get('created_timestamp', 0), reverse=True)
    
    # 重新分配ID以保持顺序
    for i, obj in enumerate(zip_objects):
        obj['id'] = i + 1
    
    return zip_objects

# 根据ID获取特定ZIP对象
def get_zip_object_by_id(zip_id):
    """根据ID获取特定的ZIP对象"""
    zip_objects = get_zip_objects()
    for obj in zip_objects:
        if obj['id'] == zip_id:
            return obj
    return None

# 获取所有文件（包括非MD文件）
def get_all_files(directory):
    """获取目录下的所有文件"""
    if not os.path.exists(directory):
        return []
    
    files = []
    for filename in os.listdir(directory):
        file_path = os.path.join(directory, filename)
        if os.path.isfile(file_path):
            try:
                # 获取文件统计信息
                stat = os.stat(file_path)
                # 在macOS上，st_birthtime更准确表示创建时间
                if hasattr(stat, 'st_birthtime'):
                    created_time = datetime.fromtimestamp(stat.st_birthtime).strftime('%Y-%m-%d %H:%M:%S')
                    created_timestamp = stat.st_birthtime
                else:
                    # 回退到ctime（在某些系统上可能是inode修改时间）
                    created_time = datetime.fromtimestamp(stat.st_ctime).strftime('%Y-%m-%d %H:%M:%S')
                    created_timestamp = stat.st_ctime
                
                modified_time = datetime.fromtimestamp(stat.st_mtime).strftime('%Y-%m-%d %H:%M:%S')
                
                files.append({
                    'name': filename,
                    'path': file_path,
                    'type': filename.split('.')[-1] if '.' in filename else 'unknown',
                    'size': os.path.getsize(file_path),
                    'created_time': created_time,
                    'modified_time': modified_time,
                    'created_timestamp': created_timestamp,
                    'modified_timestamp': stat.st_mtime
                })
            except Exception as e:
                # 如果获取文件信息失败，使用默认值
                print(f"获取文件 {filename} 信息失败: {e}")
                files.append({
                    'name': filename,
                    'path': file_path,
                    'type': filename.split('.')[-1] if '.' in filename else 'unknown',
                    'size': os.path.getsize(file_path),
                    'created_time': '无法获取',
                    'modified_time': '无法获取',
                    'created_timestamp': 0,
                    'modified_timestamp': 0
                })
    return files

